package com.whty.mongodemo.handler;

import com.whty.mongodemo.model.JsonResult;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BaseRoutingHandler {

  public void endJson(HttpServerResponse response, JsonResult jsonResult) {
    response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
    response.end(jsonResult.encodePrettily());
  }

  public void endJson(HttpServerResponse response) {
    response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
    response.end();
  }

  public Handler<AsyncResult<Message<Object>>> commonReplyHandler(HttpServerResponse response) {
    return ar -> {
      if (ar.succeeded()) {
        if (null != ar.result().body() && ar.result().body() instanceof Throwable) {
          this.endJson(response, JsonResult.failed());
        } else {
          this.endJson(response, JsonResult.success(ar.result().body()));
        }
      } else {
        log.error(ar.cause().getMessage(), ar.cause());
        this.endJson(response, JsonResult.failed());
      }
    };
  }
}
